/***Spring 2013 Group 13 Automatic Handshake Contact Information Exchanger**
  **This sketch is responsible for uploading contents of the bracelet's   **
  **external memory onto the Arduino Serial monitor. After uploading the  ** 
  **code onto the Arduino Mini open the serial monitor and stored business**
  **cards will read out. Memory can be cleard after the cards are uploaded**/

  

#include <Wire.h> 
#define extMemory 0x50

int i,j,m;
char ch;
byte pointer;


struct card {
byte name[30];
byte company[30];
byte phone[30];
byte email[30];
};

card test;

int sizename = sizeof(test.name);
int sizecompany = sizeof(test.company);
int sizephone = sizeof(test.phone);
int sizeemail = sizeof(test.email);

int sizetotal = sizename + sizecompany + sizephone + sizeemail;

void setup () {

 Serial.begin(9600);
 Wire.begin(); 
 delay(10);

 pointer = memoryRead(0);
 delay(3000);

   for (j = 1; j < pointer*sizetotal; j++) {
    Serial.print((char)memoryRead(j)); 
    delay(10);
    for (m = 0; m < pointer; m++) {
      if ((j == ((sizename) + (m*120)))||(j == ((sizename+sizecompany) + (m*120)))||(j == ((sizename+sizecompany+sizephone) + (m*120))))
        Serial.println();
      else if (j == ((sizename+sizecompany+sizephone+sizeemail) + (m*120))) {
        Serial.println();
        Serial.println();
      }
    }
  }
  Serial.println();
  Serial.println();
  Serial.println("Enter 'C' to clear memory");
}

void loop () {
  if (Serial.available() > 0) {
    ch = (char)Serial.read();
    delay(10);
    if (ch == 'C') {
      Serial.println();
      Serial.println();
      Serial.println("Clearing Memory...");
      for (j = 1; j < pointer*sizetotal; j++) {
        memoryWrite(j, 0);
        delay(7);
      }
      Serial.println();
      Serial.println("Memory is cleared!"); 
      memoryWrite(0, 0);
    }
  }  
}

void memoryWrite(int address, byte data) {
  byte highAddress;
  byte lowAddress;
 
  highAddress = highByte(address);
  lowAddress = lowByte(address);

  Wire.beginTransmission(extMemory);
  Wire.write(highAddress);
  Wire.write(lowAddress);
  Wire.write(data);
  Wire.endTransmission();

}

byte memoryRead(int address) {
  byte highAddress;
  byte lowAddress;
 
  highAddress = highByte(address);
  lowAddress = lowByte(address);    

  Wire.beginTransmission(extMemory);
  Wire.write(highAddress);
  Wire.write(lowAddress); 
  Wire.endTransmission();

  Wire.requestFrom(extMemory, 1);

    while(!Wire.available()) {

  }

  return Wire.read();
}  